package com.github.cakin.shiro.chapter5.hash.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @className: MyRealm
 * @description: 注入一个 passwordService 来加密密码
 * @date: 2020/5/18
 * @author: cakin
 */
public class MyRealm extends AuthorizingRealm {
    /**
     * 定义一个 PasswordService
     */
    private PasswordService passwordService;
    /**
     * 功能描述：从配置文件中，注入一个 DefaultPasswordService 对象
     *
     * @author cakin
     * @date 2020/5/18
     * @param passwordService 密码服务
     */
    public void setPasswordService(PasswordService passwordService) {
        this.passwordService = passwordService;
    }

    /**
     * 授权服务不实现
     * @param principals 用户身份
     * @return AuthorizationInfo 授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
    /**
     * 功能描述：从Realm中获取认证数据
     *
     * @author cakin
     * @date 2020/5/18
     * @param token 认证token
     * @return AuthenticationInfo 认证信息
     * 返回的认证信息主要是下面两项（用户身份、凭证）：
     * principals = {SimplePrincipalCollection@1177} "wu"
     * credentials = "$shiro1$SHA-512$1$$PJkJr+wlNU1VHa4hWQuybjjVPyFzuNPcPu5MBH56scHri4UQPjvnumE7MbtcnDYhTcnxSkL9ei/bhIVrylxEwg=="
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                "wu",
                passwordService.encryptPassword("123"),
                getName());
        return info;
    }
}
